/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.security.nls.support;

import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.collect.ImmutableMap;
import org.vacoor.nothing.common.json.Jacksons;
import org.vacoor.nothing.common.util.HttpUtils;
import org.vacoor.nothing.common.util.StringUtils;
import org.vacoor.nothing.security.nls.TranslationException;
import org.vacoor.nothing.security.nls.Translator;

import java.io.InputStream;
import java.util.Locale;
import java.util.Properties;

/**
 * @author vacoor
 */
public class YouDaoTranslator extends TranslatorSupport {
    private static final String API = "http://fanyi.youdao.com/openapi.do?type=data&doctype=json&version=1.1";

    public static final String KEYFROM_PROP = "youdao.keyfrom";
    public static final String KEY_PROP = "youdao.key";
    public static final Translator INSTANCE = new YouDaoTranslator();

    @Override
    public boolean accepts(Locale from, Locale to) {
        return true;
    }

    @Override
    protected String doTranslate(String text, Locale from, Locale to, Properties props) {
        LOG.debug("执行有道翻译: {}, {} -> {}", text, from, to);
        String keyfrom = props.getProperty(KEYFROM_PROP);
        String key = props.getProperty(KEY_PROP);
        if (!StringUtils.hasText(keyfrom) || !StringUtils.hasText(key)) {
            throw new TranslationException("keyfrom and key must be not empty");
        }

        InputStream is = HttpUtils.get(API, ImmutableMap.<String, Object>of("keyfrom", keyfrom, "key", key, "q", text), 10 * 1000);
        JsonNode root = Jacksons.deserialize(is, JsonNode.class);
        return root.get("translation").get(0).asText();
    }
}
